package tech.aiotcloud.city.citybigdataweb.util.jsbridge;

import android.content.Context;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;

import androidx.webkit.WebViewAssetLoader;

import java.util.HashMap;

public class WebViewAssetsIntercepter {
    private Context context;
    private static WebViewAssetLoader assetLoader = null;
    private HashMap<String, String> mMimeS = new HashMap<>();

    public WebViewAssetsIntercepter(Context context) {
        this.context = context;
        /*
           通过WebViewAssetLoader来将本地的资源转换为服务器的资源file:// -> http(s)://
        */
        assetLoader = new WebViewAssetLoader.Builder()
                .addPathHandler("/assets/", new WebViewAssetLoader.AssetsPathHandler(context))
                .addPathHandler("/res/", new WebViewAssetLoader.ResourcesPathHandler(context))
                .build();
    }

    public WebViewAssetLoader getAssetLoader() {
        return assetLoader;
    }

    public WebViewAssetsIntercepter addMime(String end, String type) {
        mMimeS.put(end, type);
        return this;
    }

    public WebResourceResponse intercepter(WebView view, WebResourceRequest request) {
        WebResourceResponse intercepted = null;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            intercepted = getAssetLoader().shouldInterceptRequest(request.getUrl());
            for (String key : mMimeS.keySet()) {
                if (request.getUrl().toString().endsWith(key)) {
                    intercepted.setMimeType(mMimeS.get(key));
                }
            }
        }
        return intercepted;
    }
}
